var Client = require('ssh2').Client
  , blessed = require('blessed')
  , EventEmitter = require('events').EventEmitter
  , eventDispatcher = new EventEmitter()
  , cfg = require(require('os').homedir().concat('/.wlog.json'))
  , files = new Array(cfg.logs.length)

for(let i = 0; i < files.length; i++) {
  files[i] = {
    output: ''
  }
}

const DEFAULT_SCROLL_OPTIONS = {
  scrollable: true,
  input: true,
  alwaysScroll: true,
  scrollbar: {
    ch: " ",
    inverse: true
  },
  keys: true,
  vi: true,
  mouse: true
}

class Dashboard {
  constructor() {
    this.screen = blessed.screen({
      title: 'wlog',
      smartCSR: true,
      fullUnicode: true,
      dockBorders: false,
      autoPadding: true
    })

    this.layoutLog()
    this.layoutLogFiles()
    this.layoutFooter()

    this.screen.key(['escape', 'q', 'C-c'], (ch, key) => {
      return process.exit(0)
    })
    this.screen.key('tab', (ch, key) => {
      this.screen.focusPrevious()
    })

    this.logFiles.focus()
    this.screen.render()

    eventDispatcher.on('logFileSwitched', (idx) => {
      this.currentOutputIndex = idx
      this.logText.log('' + files[this.currentOutputIndex].output)
      this.screen.render()
    })
    eventDispatcher.on('dataReceived', (idx) => {
      this.logText.log(files[this.currentOutputIndex].output)
      this.screen.render()
    })
    this.currentOutputIndex = 0
    this.ssh()
  }

  ssh() {
    this.client = new Client()

    this.client.on('ready', () => {
      this.logText.log('ssh connected!')
      this.screen.render()
      for (let i = 0; i < cfg.logs.length; i++) {
        files[i].output = ''
        this.client.exec(`tail -f ${cfg.logs[i].path}`, (err, stream) => {
          if (err) throw err;
          stream.on('close', (code, signal) => {
            console.log('Stream :: close :: code: ' + code + ', signal: ' + signal);
            this.client.end();
          })
          stream.on('data', (data) => {
            files[i].output += data
            eventDispatcher.emit('dataReceived', i)
          }).stderr.on('data', (data) => {
            console.log('STDERR: ' + data)
          })
        })
      }
    }).connect({
      host: cfg.ssh.host,
      port: cfg.ssh.port,
      username: cfg.ssh.username,
      privateKey: require('fs').readFileSync(cfg.ssh.privateKey)
    })
  }

  layoutFooter() {

  }

  layoutLogFiles() {
    this.logFilesBox = blessed.box({
      label: 'Files',
      left: '75%',
      width: '25%',
      height: '98%',
      border: {
        type: 'line'
      },
      padding: {
        left: 1
      },
      style: {
        fg: -1,
        border: {
          fg: 'green'
        }
      }
    })

    this.logFiles = blessed.list({
      parent: this.logFilesBox,
      padding: 1,
      style: {
        fg: -1,
        selected: {
          fg: 'blue'
        }
      },
      keys: false,
      mouse: false,
    })
    this.logFiles.size  = 0
    this.logFiles.currentIndex = 0

    this.logFiles.on('keypress', (ch, key) => {
      switch(ch) {
        case 'j':
          this.logFiles.currentIndex++
          this.logFiles.currentIndex = this.logFiles.currentIndex > this.logFiles.size - 1 ? this.logFiles.size - 1 : this.logFiles.currentIndex
          this.logFiles.down()
          break;
        case 'k':
          this.logFiles.currentIndex--
          this.logFiles.currentIndex = this.logFiles.currentIndex < 0 ? 0 : this.logFiles.currentIndex
          this.logFiles.up()
      }
      switch(ch) {
        case 'j':
        case 'k':
          eventDispatcher.emit('logFileSwitched', this.logFiles.currentIndex)
          this.screen.render()
          break;
      }
    })

    cfg.logs.forEach((e) => {
      this.logFiles.addItem(e.alias)
      this.logFiles.size++
    }, this)

    this.screen.append(this.logFilesBox)
  }

  layoutLog() {
    this.log = blessed.box({
      label: 'Log',
      padding: 1,
      width: '75%',
      height: '98%',
      scrollable: true,
      border: {
        type: 'line'
      },
      style: {
        fg: -1,
        border: {
          fg: 'green'
        }
      },
      clickable: true
    })

    this.logText = blessed.log(
      Object.assign({}, DEFAULT_SCROLL_OPTIONS, {
        parent: this.log,
        tags: true,
        width: "100%-5"
      })
    )

    this.screen.append(this.log)
  }
}

module.exports = Dashboard
